<template>
  <el-container>
    <el-header>
      <h1 style="margin-top: auto">课程详情</h1>
    </el-header>
    <el-main :key="updateKey">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <div class="container">
              <h2>{{course.courseName}}</h2>
              <button class="responsive-button" @click="studyCourse">我要学习此课程</button>
            </div>
            <p>{{course.description}}</p>
            <el-divider></el-divider>
            <h3>课程目录</h3>
            <el-tree :key="new Date().getTime()" ref="directoriesTree"
                     :data="treeData"
                     :props="defaultProps"
                     node-key="id"
                     default-expand-all
                     :expand-on-click-node="false" @node-click="handleNodeClick"
                     icon="Folder"
                     style="max-width: 600px">
            </el-tree>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card>
            <h3>课程基本信息</h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="讲师">{{course.nickname}}</el-descriptions-item>
              <el-descriptions-item label="创建课程时间">{{course.createdAt}}</el-descriptions-item>
            </el-descriptions>
          </el-card>
          <el-divider></el-divider>
          <el-card>
            <h3>课件列表</h3>
            <el-table :data="fileList" style="width: 100%" :show-header="false">
              <el-table-column prop="fileName" label="文件名" width="180" >
                <template #default="scope">
                  <div style="display: flex; align-items: center">
                    <el-icon><Files /></el-icon>
                    <span style="margin-left: 10px">{{ scope.row.fileName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="Operations">
                <template #default="scope">
                  <el-button
                      key="primary"
                      type="primary"
                      link
                      @click="previewFile(scope.row.fileId,scope.row.fileName,scope.row.fileUrl)">
                    预览
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>

  <el-dialog v-model="dialogDirectories" :title="titleName" width="1000">
    <el-form-item :label-width="200" label="目录名称">
      <el-input v-model="directoriesForm.directoryName" autocomplete="off"/>
    </el-form-item>
  </el-dialog>
</template>


<script setup>
import courseAPI from "@/api/module/course";
import directoriesAPI from "@/api/module/directories";
import {onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router"
import fileApi from "@/api/module/file";
import {Files, Timer} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";


const router = useRoute()
const updateKey = ref(0);
let course=reactive({
})

const directoriesTree = ref(null);
const dialogDirectories = ref(false);
let treeData = ref({});
let titleName = ref("");

//列表
let directoriesForm = reactive({
  directoryId:'',
  courseId:'',
  directoryName:'',
  parentDirectoryId:'',
  createdAt:''
})
//文件列表
let fileList = ref(null);
onBeforeMount(async () => {
  let courseId = router.query.courseId;
  await getDetails(courseId);
  updateKey.value ++;
})
onMounted(() => {
  getTreeData();
})

const getTreeData = async () => {
  let courseId = router.query.courseId;
  directoriesAPI.list(courseId).then(res=>{
    if(res.code===200){
      treeData.value=res.data;
    }
  })
}

const getDetails =  async (courseId) => {
  await courseAPI.detailCourse(courseId).then((res) => {
    course = res.data;
  }).catch((err) => {
    console.log(err)
  });
}

const defaultProps = {
  children: 'children',
  label: 'name',
}


const handleNodeClick = (data) => {
  const directoryId = data.id;
  fileApi.list(directoryId).then((res) => {
    if (res.code === 200){
      fileList.value = res.data;
      console.log(fileList.value);
    }
  }).catch((err) => {
    console.log(err)
  })

}

const previewFile = ((fileId,fileName,fileUrl)=>{
  if(null == fileUrl){
    ElMessage.error("您好，目前您没有权限观看此课程，请先学习此课程！");
  }else {
    let previewUrl = 'http://localhost:18000/course/file/preview/' +  fileId  +'?params=1' + '&fullfilename='+fileName;
    window.open('http://127.0.0.1:8012/onlinePreview?url='+base64UrlEncode(previewUrl));
  }
})

const base64UrlEncode = ((str) => {
  return btoa(unescape(encodeURIComponent(str)))
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=+$/, '');
})

//点击学习
const studyCourse = ((str) => {
  ElMessageBox.confirm(
      '确定要学习此课程吗?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    let courseId = router.query.courseId;
    //当前登录用户id
    courseAPI.study(courseId).then((res) => {
      if (res.code === 200){
        ElMessage({
          message: '学习成功',
          type: 'success',
        })
      }else {
        ElMessage.error(res.msg);
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消学习',
    })
  })
})
</script>


<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  line-height: 60px;
}

.el-main {
  padding: 20px;
}

.el-card {
  margin-bottom: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.container {
  display: flex; /* 使用 Flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 500px; /* 设置标题和按钮之间的间距 */
  //background: #80c7ff;
}

.responsive-button {
  font-size: 16px; /* 相对于根元素的字体大小 */
  background: #409EFF;
  width: 150px;
  height: 40px;
  color: white;
}
</style>